<?php

namespace App\Console\Commands;

use App\Services\HeliusService;
use GuzzleHttp\Client;
use Illuminate\Console\Command;


class Test extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:test';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    protected $helius;

    /**
     * Execute the console command.
     */
    public function handle()
    {

        $this->getCollectionTransactions('DgtiGmLYRmr4rML4M1oMDgNkA9ctZb8BBdTX1z4Ynbpe');
    }

    /**
     * 获取集合所有交易
     */
    public function getCollectionTransactions(string $collectionAddress)
    {
        $this->helius = new HeliusService();
        // 1. 获取集合所有NFT
        $nfts = $this->helius->getCollectionNFTs($collectionAddress);

        dd($nfts);
        // 2. 限制处理的NFT数量（防止超时）
        $limitNfts = 100;
        $nfts = array_slice($nfts, 0, $limitNfts);

        // 3. 获取每个NFT的交易签名
        $allSignatures = [];
        foreach ($nfts as $nft) {
            $signatures = $this->helius->getSignaturesForAsset($nft['id']);
            $allSignatures = array_merge($allSignatures, $signatures);
        }
        // 4. 去重签名
        $uniqueSignatures = collect($allSignatures)
            ->unique('signature')
            ->pluck('signature')
            ->toArray();

        // 5. 获取交易详情（分批处理）
        $transactions = [];
        $batchSize = 10; // 每批处理10个交易
        foreach (array_chunk($uniqueSignatures, $batchSize) as $batch) {
            foreach ($batch as $signature) {
                $transaction = $this->helius->getTransaction($signature);
                if ($transaction) {
                    $transactions[] = $this->parseTransaction($transaction);
                }
            }
            sleep(1); // 防止速率限制
        }

        // 6. 按时间排序
        usort($transactions, function ($a, $b) {
            return $b['timestamp'] <=> $a['timestamp'];
        });

        $data = [
            'total_transactions' => count($transactions),
            'transactions' => $transactions
        ];

        dd($data);
    }

    /**
     * 解析交易数据
     */
    protected function parseTransaction(array $transaction)
    {
        $meta = $transaction['meta'] ?? [];
        $message = $transaction['transaction']['message'] ?? [];

        return [
            'signature' => $transaction['transaction']['signatures'][0] ?? null,
            'timestamp' => $transaction['blockTime'] ?? null,
            'fee' => $meta['fee'] ?? 0,
            'successful' => !($meta['err'] ?? false),
            'instructions' => $message['instructions'] ?? [],
            'accounts' => $message['accountKeys'] ?? []
        ];
    }
}
